package org.example.lib;

import org.example.annotations.route.RequestMapping;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Router {

    public static final Router instance = new Router();

    private final Map<RequestMapping.HttpMethod, Map<String, Route>> staticRoutes = new HashMap<>(){{
        put(RequestMapping.HttpMethod.GET, new HashMap<>());
        put(RequestMapping.HttpMethod.POST, new HashMap<>());
        put(RequestMapping.HttpMethod.PUT, new HashMap<>());
        put(RequestMapping.HttpMethod.DELETE, new HashMap<>());
    }};
    private final Map<RequestMapping.HttpMethod, Set<Route>> dynamicRoutes = new HashMap<>(){{
        put(RequestMapping.HttpMethod.GET, new HashSet<>());
        put(RequestMapping.HttpMethod.POST, new HashSet<>());
        put(RequestMapping.HttpMethod.PUT, new HashSet<>());
        put(RequestMapping.HttpMethod.DELETE, new HashSet<>());
    }};

    public void addRoute(Route route, RequestMapping.HttpMethod method) {
        if (route.isStatic()){
            staticRoutes.get(method).put(route.getPath(), route);
        }else{
            dynamicRoutes.get(method).add(route);
        }
    }

    public Route findRoute(String path, RequestMapping.HttpMethod method) {
        Route route = staticRoutes.get(method).get(path);
        if (route != null) {
            return route;
        }
        for (Route dynamicRoute : dynamicRoutes.get(method)) {
            if (dynamicRoute.match(path)) {
                return dynamicRoute;
            }
        }
        return null;
    }
}
